"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import Input from "@/components/custom-ui/input";
import { Eye, EyeOff, Lock, Loader, User2Icon } from "lucide-react";
import { useEffect, useState } from "react";
import {
  RegisterVerificationFormData,
  RegisterVerificationSchema,
} from "@/schemas/auth";
import { useMutation } from "@tanstack/react-query";
import { RegisterVerificationAction } from "@/actions/auth";
import { useRouter, useSearchParams } from "next/navigation";
import { VerificationTokenType } from "@/lib/enums";
import { useTranslations } from "next-intl";

export default function VerificationForm() {
  const t = useTranslations("authPages");
  const tZod = useTranslations("zod");
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const email = searchParams.get("email");
  const [pwdShow, setPwdShow] = useState(false);
  const form = useForm<RegisterVerificationFormData>({
    resolver: zodResolver(RegisterVerificationSchema(tZod)),
    defaultValues: {
      type: VerificationTokenType.RegisterToken,
      token: "",
      first_name: "",
      last_name: "",
      password: "",
      email: "",
    },
  });
  const router = useRouter();
  const mutation = useMutation({
    mutationFn: RegisterVerificationAction,
    onSuccess: (data) => {
      if (data.success) {
        toast.success(data.success);
        router.push("/auth/login");
      }
      if (data.error) {
        toast.error(data.error);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  const { mutate, isPending } = mutation;

  useEffect(() => {
    if (token) {
      form.setValue("token", token as string);
    }
    if (email) {
      form.setValue("email", email as string);
    }
  }, [email, form, token]);
  const onSubmit = (values: RegisterVerificationFormData) => mutate(values);
  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-6">
        <FormField
          control={form.control}
          name="first_name"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-muted-foreground">{t("firstName")}</FormLabel>
              <FormControl>
                <Input
                  className="h-12 flex items-center"
                  placeholder="example"
                  {...field}
                  startIcon={<div className="w-10 flex justify-center"><User2Icon className="h-4 w-4" /></div>}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="last_name"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-muted-foreground">{t("lastName")}</FormLabel>
              <FormControl>
                <Input
                  className="h-12 flex items-center"
                  placeholder="example"
                  {...field}
                  startIcon={<div className="w-10 flex justify-center"><User2Icon className="h-4 w-4" /></div>}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel className="text-muted-foreground">{t("password")}</FormLabel>
              <FormControl>
                <Input
                  className="h-12"
                  type={!pwdShow ? "password" : "text"}
                  placeholder="******"
                  {...field}
                  startIcon={<div className="w-10 flex justify-center"><Lock className="h-4 w-4" /></div>}
                  endIcon={
                    <div
                      onClick={() => setPwdShow(!pwdShow)}
                      className="w-10 flex justify-center cursor-pointer"
                    >
                      {pwdShow ? (
                        <Eye className="h-4 w-4" />
                      ) : (
                        <EyeOff className="h-4 w-4" />
                      )}
                    </div>
                  }
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button
          className="w-full h-12 cursor-pointer select-none"
          type="submit"
          disabled={isPending}
        >
          {isPending ? <Loader className="animate-spin" /> : null}
          {t("register")}
        </Button>
      </form>
    </Form>
  );
}
